package 文件小程序;

import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:查找文件内容
 * User: lenovo
 * Date: 2022-10-17
 * Time: 19:04
 */
public class demo3 {
    public static void main(String[] args) {
        //1.输入文件路径
        System.out.println("请输入文件名:");
        Scanner scanner = new Scanner(System.in);
        File rootDir = new File(scanner.next());
        //请输入查找的内容
        System.out.println("请输入查找的内容:");
        String toFind = new String(scanner.next());
        //递归遍历
        scan(rootDir,toFind);

    }

    private static void scan(File rootDir, String toFind) {
        File[] files = rootDir.listFiles();
        if(files == null){
            return;
        }
        for(File file:files){
            //是是目录继续递归遍历
            if(file.isDirectory()){
                scan(file,toFind);
            }else{
                //不是目录,检查内容
                check(file,toFind);
            }
        }
    }

    private static void check(File file, String toFind) {
        //文件名是否包含toFind
        if(file.getName().contains(toFind)){
            System.out.println(file.getParent()+"文件名包含"+toFind);
        }
        //判断文件内容里是否包含toFind
        try(InputStream inputStream =  new FileInputStream(file)){
            Scanner scanner = new Scanner(inputStream);
            StringBuilder stringBuilder =new StringBuilder();
            while(scanner.hasNextLine()){
                stringBuilder.append(scanner.nextLine()+"/n");
            }
            if(stringBuilder.indexOf(toFind)>-1){
                System.out.println(file.getParent()+"文件内容包含"+toFind);
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
